/*
 * Copyright (c)  2015, Newtouch
 * All rights reserved. 
 *
 * $id: HttpsKit.java 9552 2015年6月21日 下午10:19:31 WangLijun$
 */
package com.xiqing.wechat.web.util;


import org.apache.commons.lang.CharEncoding;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.util.Map;
import java.util.Map.Entry;

/**
 * <p>
 * Title:
 * </p>
 * <p>
 * Description:
 * </p>
 * <p>
 * Copyright: Copyright (c) 2015
 * </p>
 * <p>
 * Company: Newtouch
 * </p>
 * 
 * @author WangLijun
 * @version 1.0
 */
public class HttpsKit {
	
	/** 日志类 */
	private static final Logger logger = LoggerFactory.getLogger(HttpsKit.class);
	/** 编码 */
	private static final String DEFAULT_CHARSET = CharEncoding.UTF_8;
	/** GET请求 */
	@SuppressWarnings("unused")
	private static final String GET = HttpGet.METHOD_NAME; // GET
	/** POST请求 */
	public static final String POST = HttpPost.METHOD_NAME;// POST
	/** HTTP　请求参数问号 ? */
	public static final String QUESTION_MARK = "?";
	/** ampersand & */
	public static final String AMPERS_AND = "&";
	/** 等号= */
	public static final String EQUALS_SIGN = "=";

	private static CloseableHttpClient httpclient = null;
	/***
	 * 参数
	 * @param url
	 * @param params
	 * @return
	 */
	public static String execute(String url, Map<String, String> params) {
		String result=StringUtils.EMPTY;
		if (httpclient == null) {
			httpclient = createHttpsClient();
		}
		url=initParams(url,params);
		HttpGet httpGet=null;
		try {
			httpGet= new HttpGet (url);
			HttpResponse httpResp = httpclient.execute(httpGet);
			int statusCode = httpResp.getStatusLine().getStatusCode();
			if (statusCode == 200) {
				result=EntityUtils.toString(httpResp.getEntity());
			}
		} catch (ClientProtocolException e) {
			logger.error(e.getMessage(),e);
		} catch (IOException e) {
			logger.error(e.getMessage(),e);
		}catch (Exception e){
			logger.error(e.getMessage(),e);
		}finally {
			 if(httpGet!=null){
				 httpGet.releaseConnection ();
			 }

		}
		return result;
	}

	/**
	 * 功能描述: 构造请求参数
	 * 
	 * @return 返回类型:
	 * @throws UnsupportedEncodingException
	 */
	public static String initParams(String url, Map<String, String> params) {
		if (CollectionUtils.isEmpty(params)) {
			return url;
		}
		StringBuilder sb = new StringBuilder(url);
		if (url.indexOf(QUESTION_MARK) == -1) {
			sb.append(QUESTION_MARK);
		}
		try {
			sb.append(map2Url(params));
		} catch (UnsupportedEncodingException e) {
			//throw new ServiceException(ServiceErrorCode.HTTP_ENCODING, e);

		}
		return sb.toString();
	}
	
	/**
	 * map构造url
	 * 
	 * @return 返回类型:
	 * @throws UnsupportedEncodingException
	 */
	public static String map2Url(Map<String, String> paramToMap)
			throws UnsupportedEncodingException {
		if (null == paramToMap || paramToMap.isEmpty()) {
			return null;
		}
		StringBuffer url = new StringBuffer();
		boolean isfist = true;
		for (Entry<String, String> entry : paramToMap.entrySet()) {
			if (isfist) {
				isfist = false;
			} else {
				url.append(AMPERS_AND);
			}
			url.append(entry.getKey()).append("=");
			String value = entry.getValue();
			if (StringUtils.isNotEmpty(value)) {
				url.append(URLEncoder.encode(value, DEFAULT_CHARSET));
			}
		}
		return url.toString();
	}

	/**
	 * 创建对象
	 * 
	 * @return CloseableHttpClient
	 */
	public static CloseableHttpClient createHttpsClient() {

		X509TrustManager x509mgr = new X509TrustManager() {


			public void checkClientTrusted(
					java.security.cert.X509Certificate[] chain, String authType)
					throws CertificateException {
				// TODO Auto-generated method stub

			}


			public void checkServerTrusted(
					java.security.cert.X509Certificate[] chain, String authType)
					throws CertificateException {
				// TODO Auto-generated method stub

			}


			public java.security.cert.X509Certificate[] getAcceptedIssuers() {
				// TODO Auto-generated method stub
				return null;
			}

		};

		SSLContext sslContext = null;

		try {
			sslContext = SSLContext.getInstance("TLS");

		} catch (NoSuchAlgorithmException e) {

		}

		try {

			sslContext.init(null, new TrustManager[] { x509mgr }, null);

		} catch (KeyManagementException e) {

		}

		SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory (

		sslContext,

		SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

		return HttpClients.custom().setSSLSocketFactory(sslsf).build();

	}
}
